package org.gol.paxos;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.gol.paxos.member.Citizen;
import org.gol.paxos.member.Senator;
import org.gol.paxos.role.Acceptor;
import org.gol.paxos.role.Proposer;

/**
 * @package org.gol.paxos.client
 * @description 【议会】
 * @author Goliath
 * @createTime 2012-11-21 下午1:32:17
 * @modifyTime
 */
public class Parliament {

	public Parliament(int maxAcceptorNum) {
		this.maxAcceptorNum = maxAcceptorNum;
		// 向议会中增加参议员
		for (int i = 0; i < maxAcceptorNum; i++) {
			this.addAcceptor();
		}
	}

	/**
	 * 议员席位最大数
	 */
	private int maxAcceptorNum;
	/**
	 * 议员的席位
	 */
	public Map<String, Acceptor> acceptorPositions = Collections.synchronizedMap(new HashMap<String, Acceptor>());
	/**
	 * 提案人的席位
	 */
	public Map<String, Proposer> proposerPositions = Collections.synchronizedMap(new HashMap<String, Proposer>());

	public void addAcceptor() {
		for (int i = 0; i < maxAcceptorNum; i++) {
			String positionNo = "S" + i;
			if (acceptorPositions.get(positionNo) == null) {
				Acceptor oSenator = new Senator(positionNo);
				acceptorPositions.put(positionNo, oSenator);
				oSenator.standBy();
				System.out.println("添加了一位参议员，席位号:" + positionNo);
				return;
			}
		}
		System.out.println("参议员席位的已满，席位数" + maxAcceptorNum + ",没有空闲的席位!!");
	}

	public void addCitizen(Citizen oCitizen) {
		if (proposerPositions.get(oCitizen.getPositionNo()) == null) {
			proposerPositions.put(oCitizen.getPositionNo(), oCitizen);
			oCitizen.standBy();
			System.out.println("添加了一位公民代表，席位号:" + oCitizen.getPositionNo());
			return;
		}
	}

	public int getMaxSenatorNum() {
		return maxAcceptorNum;
	}

	public void setMaxSenatorNum(int maxSenatorNum) {
		this.maxAcceptorNum = maxSenatorNum;
	}

}
